package tech.edwardvan.designpattern.pattern.behavioral.strategy;

import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import lombok.Setter;
import lombok.extern.slf4j.Slf4j;

import java.util.HashMap;
import java.util.Map;

/**
 * 策略模式
 *
 * @author EdwardVan
 */
@Slf4j
public class StrategyDemo3 {

    public static void main(String[] args) {
        //使用策略模式获取id
        IdGenerator idGenerator = new IdGenerator();
        idGenerator.setIdType(IdStrategy.Type.UUID);
        String id = idGenerator.generate();
        log.info("生成的id为:{}", id);
    }

    /**
     * id策略接口
     */
    private interface IdStrategy {

        String generateId();

        /**
         * 策略类型
         */
        enum Type {
            UUID, OBJECT_ID, SNOW_FLAKE
        }
    }

    private static class UUIdStrategy implements IdStrategy {

        @Override
        public String generateId() {
            return IdUtil.randomUUID();
        }
    }

    private static class ObjectIdStrategy implements IdStrategy {

        @Override
        public String generateId() {
            return IdUtil.objectId();
        }
    }

    private static class SnowFlakeIdStrategy implements IdStrategy {

        private static Snowflake snowflake = IdUtil.getSnowflake();

        @Override
        public String generateId() {
            return snowflake.nextIdStr();
        }
    }


    /**
     * id生成器(优化版)
     */
    private static class IdGenerator {

        private static Map<IdStrategy.Type, IdStrategy> strategyMap = new HashMap();

        static {
            strategyMap.put(IdStrategy.Type.UUID, new UUIdStrategy());
            strategyMap.put(IdStrategy.Type.OBJECT_ID, new ObjectIdStrategy());
            strategyMap.put(IdStrategy.Type.SNOW_FLAKE, new SnowFlakeIdStrategy());
        }

        @Setter
        private IdStrategy.Type idType;

        public String generate() {
            IdStrategy idStrategy = strategyMap.get(idType);
            return idStrategy.generateId();
        }
    }
}
